#!/usr/bin/env python

import cgi
import wsgiref.handlers
import os
from google.appengine.api import users
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.api import urlfetch
import xml.etree.ElementTree as ET
from db_weather import DbWeather
import codecs
from xml.dom import minidom

"""
        proc = lambda tnlist, conds : [ \
            [temp.getAttribute('data') for temp in conds.getElementsByTagName(tagname)][0] \            for tagname in (tnlist) ]        xmldoc = minidom.parseString(result.content.decode("gb2312").encode("UTF-8"))        curconds = xmldoc.getElementsByTagName("forecast_conditions")        (low, high, condition, day_of_week) = proc(('low', 'high', 'condition', 'day_of_week'), curconds[0])
"""
class Weather(webapp.RequestHandler):
    def get(self):
        url = "http://www.google.com/ig/api?hl=zh-cn&weather=Hangzhou"
        #url = "http://www.google.com/ig/api?weather=Hangzhou"
        result = urlfetch.fetch(url=url)

        #self.response.out.write(result.content)
        #"""
        #result_xml = ET.fromstring(result.content)
        result_xml = ET.fromstring(result.content.decode("gb2312").encode("UTF-8"))
        low = result_xml.find('weather/forecast_conditions/low').attrib["data"]
        high = result_xml.find('weather/forecast_conditions/high').attrib["data"]
        condition = result_xml.find('weather/forecast_conditions/condition').attrib["data"]
        day_of_week = result_xml.find('weather/forecast_conditions/day_of_week').attrib["data"]
        #"""
        dbweather = DbWeather()
        dbweather.low = low
        dbweather.high = high
        dbweather.condition = condition
        dbweather.day_of_week = day_of_week
        dbweather.put()
    
    def post(self):
        pass

def main():
  application = webapp.WSGIApplication([('/.*', Weather),], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
